<template>
  <a-modal :visible="show" title="角色权限" :footer="false" @cancel="closeIt">
    <a-tree v-model:checked-keys="checkedKeys" :field-names="{
      key: 'permissionId',
      title: 'permissionName',
      icon: ''
    }" :checkable="true" :check-strictly="true" :data="treeData" @check="onCheck" />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { toTree } from '@/utils';
import { getAppPerms, getRolePerms, bindPerm, unbindPerm } from '@/api/dashboard/perm';
import { Message } from '@arco-design/web-vue';

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  appid: {
    type: Number,
    default: 0
  },
  roleid: {
    type: Number,
    default: 0
  }
});

const emit = defineEmits(['close']);
function closeIt() {
  emit('close');
}

const checkedKeys = ref([]);
const treeData = ref([] as Array<any>);

async function getAll() {
  let data = await getAppPerms();
  treeData.value = toTree(data.items, 'permissionId');
}

async function getRolePerm() {
  let data = await getRolePerms(props.roleid);
  checkedKeys.value = data.map((a: any) => a.permissionId);
}

let aid = 0, rid = 0;
watch(props, async (newp, oldp) => {
  if (aid !== newp.appid) {
    await getAll();
  }
  if (rid !== newp.roleid) {
    await getRolePerm();
  }
  aid = newp.appid;
  rid = newp.roleid;
});

function onCheck(checkedKeys: Array<number>, data: any) {
  let permissionId = data.node?.permissionId;
  if (data.checked) {
    bindPerm(rid, permissionId);
    Message.success('分配权限成功。');
  } else {
    unbindPerm(rid, permissionId);
    Message.success('解除权限成功。');
  }
}
</script>
